import { ref } from "vue"
import { ElMessage } from "element-plus"
export const useMyTable = (api: (params: any) => Promise<any>, searchParams: object = {}, isPage: boolean = true) => {
  const tableData = ref<any[]>([])
  const pageIndex = ref<number>(1)
  const pageSize = ref<number>(10)
  const totalSize = ref<number>(0)
  const params = ref<any>({})

  /**
   * @description 获取表格数据
   * @return void
   * */
  const getTableData = async () => {
    if (!api) return
    // Object.assign(params.value, searchParams)
    try {
      const res = await api({ pageIndex: pageIndex.value, pageSize: isPage ? pageSize.value : 99999, ...params.value })
      tableData.value = res.data.result
      totalSize.value = res.data.totalCount
    } catch (error) {
      ElMessage.error("获取数据失败")
      console.log(error)
    }
  }

  /**
   * @description 更新搜索参数
   * @return void
   * */
  const updateParams = (val: any) => {
    console.log(456, params.value)
    params.value = val
  }
  /**
   * @description 表格数据重置
   * @return void
   * */
  const resetTableData = () => {
    pageIndex.value = 1
    getTableData()
  }

  /**
   * @description 每页条数改变
   * @param {Number} val 当前条数
   * @return void
   * */
  const handleSizeChange = (val: number) => {
    pageIndex.value = 1
    pageSize.value = val
    getTableData()
  }

  /**
   * @description 当前页改变
   * @param {Number} val 当前页
   * @return void
   * */
  const handleCurrentChange = (val: number) => {
    pageIndex.value = val
    getTableData()
  }

  return {
    tableData,
    pageIndex,
    pageSize,
    totalSize,
    getTableData,
    resetTableData,
    updateParams,
    handleSizeChange,
    handleCurrentChange
  }
}
